/**
 * 
 */
package photosalvage.entity;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.TypedQuery;

import photosalvage.util.JPAUtils;

import com.google.inject.persist.Transactional;

/**
 * @author shumpei
 *
 */
public class OwnerRepository extends BaseRepository<Owner, Long> {

	@Inject
	PlaceRepository placeRepository;
	
	@Transactional
	public List<Owner> findByPlace(Long placeId) {
		TypedQuery<Owner> q =
			getEntityManager().createQuery(
					"select o from Owner o where o.place.id = :placeId", Owner.class);
		q.setParameter("placeId", placeId);
		return q.getResultList();
	}
	
	@Transactional
	public Owner findByNumber(String placeNum, String ownerNum) {
		TypedQuery<Owner> q =
			getEntityManager().createQuery(
					"select o from Owner o where o.place.number = :placeNum and o.number = :ownerNum", Owner.class);
		q.setParameter("placeNum", placeNum);
		q.setParameter("ownerNum", ownerNum);
		return JPAUtils.getSingleOrNull(q);
	}
	
	@Transactional
	public Owner findOrCreateByNumber(String placeNum, String ownerNum) {
		Owner o = findByNumber(placeNum, ownerNum);
		if (o == null) {
			o = new Owner();
			o.setNumber(ownerNum);
			Place place = placeRepository.findOrCreateByNumber(placeNum);
			o.setPlace(place);
			persist(o);
		}
		return o;
	}
}
